package detector.audio.processing;

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;

import edu.washington.cs.sounddetector.server.api.object.*;
/**
 * Holds a short clip of recorded audio.
 * @author Kyle
 *
 */
public class AudioClip {
	private byte[] record;
	private List<PeakEvent> peakEvents;
	private static SoundFormat sf;
	
	/**
	 * Create a new audioclip with the passed
	 * audio data, where each array index represents a sample
	 * @param record array of recorded samples
	 */
	public AudioClip(short[] record, List<PeakEvent> peakEvents) {
		if (sf == null) {
			sf = new SoundFormat(
					44100,
					16,
					1,
					true,
					true
			);
		}
		this.peakEvents = peakEvents;
		//Convert to bytes in soundformat
		ByteBuffer byteBuf = ByteBuffer.allocate(record.length*2);
		for (int i = 0; i < record.length; i++) {
			byteBuf.putShort(record[i]);
		}
		this.record = byteBuf.array();
	}
	
	/**
	 * 
	 * @return the peakevents for this audioclip
	 */
	public List<PeakEvent> getPeakEvents() {
		return Collections.unmodifiableList(peakEvents);
	}

	/**
	 * 
	 * @return the length of the audio clip, in seconds
	 */
	public int getLengthInSamples() {
		return record.length;
	}

	/**
	 * 
	 * @return an array of bytes representing the audio data with
	 * the getSoundFormat()'s format.
	 * Behavior unspecified if record is modified
	 */
	public byte[] getBytes() {
		
		return record;
	}

	public static SoundFormat getSoundFormat() {
		if (sf == null) {
			sf = new SoundFormat(
					44100,
					16,
					1,
					true,
					true
			);
		}
		return sf;			
	}

}
